package com.wuhuiyue.controller;


import cn.hutool.json.JSON;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.wuhuiyue.aop.MyAnn;
import com.wuhuiyue.entity.Channel;
import com.wuhuiyue.entity.Result;
import com.wuhuiyue.entity.User;
import com.wuhuiyue.service.IChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hy-woo
 * @since 2022-06-14
 */
@RestController
@RequestMapping("/channel")
public class ChannelController {


    @Autowired
    IChannelService channelService;

    @RequestMapping("/upload")
    public Result upload(MultipartFile[] file) throws IOException {
        for (MultipartFile multipartFile : file) {
            multipartFile.transferTo(new File("d:/test/" + multipartFile.getOriginalFilename()));
            String fileName = "d:/test/" + multipartFile.getOriginalFilename();
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            // 这里每次会读取100条数据 然后返回过来 直接调用使用数据就行
            EasyExcel.read(fileName, Channel.class, new PageReadListener<Channel>(dataList -> {
                for (Channel demoData : dataList) {
                    channelService.save(demoData);
                }
            })).sheet().doRead();
        }
        return Result.OK();
    }

    @MyAnn
    @RequestMapping("/save")
    public Result save(@RequestBody Channel channel){
       /* User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!user.getRole().equals("ADMIN")){
            return Result.failed(201,"只有管理员可以操作");
        }*/
        channel.setCreated(new Date());
        boolean b = channelService.saveOrUpdate(channel);
        return b?Result.OK():Result.failed(202,"保存失败");
    }

}
